package com.jy.adscm.operation.cg.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jy.adscm.bean.system.JyUser;
import com.jy.adscm.exception.AdscmSystemException;
import com.jy.adscm.operation.cg.bean.*;
import com.jy.adscm.operation.cg.mapper.mysql.*;
import com.jy.adscm.operation.cg.service.CgPurchasePlanService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.jy.adscm.operation.mscyb.bean.JqylMaterial;
import com.jy.adscm.operation.mscyb.mapper.mysql.JqylMaterialMapper;
import com.jy.adscm.operation.purchase.bean.CreatePlan;
import com.jy.adscm.security.utils.Token;
import com.jy.adscm.system.mapper.mysql.JyUserMapper;
import com.jy.adscm.utils.AdscmBaseUtils;
import com.jy.adscm.utils.AdscmDateUtils;
import com.jy.adscm.zltx.bean.JyDrawingType;
import com.jy.adscm.zltx.mapper.mysql.JyDrawingTypeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 采购计划 服务实现类
 * </p>
 *
 * @author zyl
 * @since 2019-07-07
 */
@Service
public class CgPurchasePlanServiceImpl extends ServiceImpl<CgPurchasePlanMapper, CgPurchasePlan> implements CgPurchasePlanService {
    @Autowired
    CgSupplierMapper cgSupplierMapper;
    @Autowired
    CgBomMapper cgBomMapper;
    @Autowired
    CgBomSupplierMapper cgBomSupplierMapper;
    @Autowired
    JyUserMapper jyUserMapper;
    @Autowired
    CgTaskMapper cgTaskMapper;
    @Autowired
    CgTaskDetailMapper cgTaskDetailMapper;
    @Autowired
    JyDrawingTypeMapper  jyDrawingTypeMapper;
    @Autowired
    CgMaterialMapper cgMaterialMapper;
    @Autowired
    JqylMaterialMapper jqylMaterialMapper;
    /**
     * 生成采购计划
     * @param createCgPlan
     * @return
     * @throws AdscmSystemException
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean createPlan(CreateCgPlan createCgPlan, Token token) throws AdscmSystemException {
         //获取上一次最大的令号
          Integer makeNo=1;
          Integer lastMakeNo=1;
        Wrapper<CgPurchasePlan> cgPurchasePlanWrapper=new EntityWrapper<>();
        cgPurchasePlanWrapper.orderBy("make_no",false);
        cgPurchasePlanWrapper.eq("type",createCgPlan.getCgType());
        cgPurchasePlanWrapper.last("limit 1");
        List<CgPurchasePlan> cgPurchasePlans = super.selectList(cgPurchasePlanWrapper);
        if (cgPurchasePlans!=null  && cgPurchasePlans.size()>0){
            CgPurchasePlan cgPurchasePlan = cgPurchasePlans.get(0);
            makeNo=cgPurchasePlan.getMakeNo()+1;
        }
        //根据图纸型号拿出这个图纸对应的bom清单
        QueryCgBom bom=new QueryCgBom();
        bom.setMachineType(createCgPlan.getType());
        bom.setType(createCgPlan.getCgType());
        List<CgBom> cgBoms = cgBomMapper.queryBoms(bom);
        //遍历bom清单
        for (CgBom cgBom : cgBoms) {
            //每个bom生成一个单独的采购计划
            CgPurchasePlan cgPurchasePlan =new CgPurchasePlan();
            //bom里面的
            CgMaterial cgMaterial = cgBom.getCgMaterial();

            CgBomSupplier cgBomSupplier = cgBom.getCgBomSupplier();
            if(!AdscmBaseUtils.getInstance().isNotEmpty(cgBomSupplier,null)){
                throw new AdscmSystemException("物料："+cgMaterial.getName()+"未配置供应商，请到菜单：物料与供应商配置");
            }

            cgPurchasePlan.setState(0);
            cgPurchasePlan.setBid(cgMaterial.getId().longValue());
            cgPurchasePlan.setSid(cgBomSupplier.getSid());
            cgPurchasePlan.setMakeNo(makeNo);
            cgPurchasePlan.setMinPurchase(cgBomSupplier.getMinPurchase().toString());
            cgPurchasePlan.setCreateTime(new Date());
            cgPurchasePlan.setCreator(token.getUser().getId().toString());
            //计算购买数量
            if (!AdscmBaseUtils.getInstance().isNotEmpty(cgBom.getNums(),null)){
                 throw  new AdscmSystemException(cgBom.getName()+"采购数量为空");
            }
            if (!AdscmBaseUtils.getInstance().isNotEmpty(cgMaterial.getNo(),null)){
                throw  new AdscmSystemException(cgBom.getName()+"采购损耗系数为空");
            }
           float nums= cgBom.getNums()*createCgPlan.getNum()*cgMaterial.getNo();
            cgPurchasePlan.setNeedNums(nums);
             //查看是否有剩余量如果有剩余量 就不用购买
            Float remaining = cgMaterial.getRemaining();
            remaining=remaining-nums;
            if (remaining<0){
                //需要购买
                remaining=-remaining;
                if (cgBomSupplier.getMinPurchase()>remaining){
                    cgPurchasePlan.setActNums(cgBomSupplier.getMinPurchase().floatValue());
                    cgMaterial.setRemaining(cgBomSupplier.getMinPurchase()-remaining);
                }else {
                    cgMaterial.setRemaining(0f);
                    cgPurchasePlan.setActNums(remaining);
                }
                cgMaterialMapper.updateById(cgMaterial);
            }else {
                cgMaterial.setRemaining(remaining);
                cgMaterialMapper.updateById(cgMaterial);
                continue;

            }
            //设置单价
            cgPurchasePlan.setPrice(cgBomSupplier.getPrice());
            //计算总价
            float total= cgPurchasePlan.getActNums()*cgPurchasePlan.getPrice();
            DecimalFormat df = new DecimalFormat("#.00");
            String totalStr = df.format(total);
            cgPurchasePlan.setTotal(totalStr);
            //计算到货日期  需求日期-物料提前期
            Date planArriveDate = AdscmDateUtils.getThatDate(createCgPlan.getNeedDate(), 0, Calendar.DATE);
            cgPurchasePlan.setPlanArriveDate(planArriveDate);
            //计算下单时间   到货日期-采购提前期
            Date orderDate = AdscmDateUtils.getThatDate(cgPurchasePlan.getPlanArriveDate(), -cgBomSupplier.getPredate(), Calendar.DATE);
            cgPurchasePlan.setOrderDate(orderDate);
            //计算付款时间  到货日期+付款周期
            CgSupplier cgSupplier = cgBom.getCgSupplier();
            if (AdscmBaseUtils.getInstance().isNotEmpty(cgSupplier,null)){
                if (AdscmBaseUtils.getInstance().isNotEmpty(cgSupplier.getPaymentPeriod(),null)){
                    Date payDate = AdscmDateUtils.getThatDate(cgPurchasePlan.getPlanArriveDate(), cgSupplier.getPaymentPeriod(), Calendar.DATE);
                    cgPurchasePlan.setPayDate(payDate);
                }else {
                    cgPurchasePlan.setPayDate(planArriveDate);
                }
            }
            Integer paymentMethod = cgSupplier.getPaymentMethod();
            Integer paymentPeriod = cgSupplier.getPaymentPeriod();
            if(!AdscmBaseUtils.getInstance().isNotEmpty(paymentMethod,null)){
                paymentPeriod=1;
            }else {
                if (paymentMethod==1){//预付款
                    if (!AdscmBaseUtils.getInstance().isNotEmpty(paymentPeriod,null)){
                        paymentPeriod=1; //若为空付款周期为1天
                    }
                }
                if (paymentMethod==2){//款到付款
                    paymentPeriod=-cgBomSupplier.getPredate();
                }
                if (paymentMethod==3){
                    if (!AdscmBaseUtils.getInstance().isNotEmpty(paymentPeriod,null)){
                        paymentPeriod=1; //若为空付款周期为1天
                    }
                }
                Date latePaydate = AdscmDateUtils.getFormateDate(AdscmDateUtils.getThatDate(planArriveDate, paymentPeriod, Calendar.DATE));
                cgPurchasePlan.setPayDate(latePaydate);
                if (paymentMethod==4){
                    //根据这个到货日期算和月结号计算支付时间
                    DecimalFormat decimalFormat=new DecimalFormat("00");
                    String format = decimalFormat.format(paymentPeriod);
                    String arriveDate = AdscmDateUtils.getNowOnlyDateFomat1(planArriveDate).substring(0,8)+format;
                    Date date = AdscmDateUtils.parseDate(arriveDate);
                    date= AdscmDateUtils.getThatDate(date,1,Calendar.MONTH);
                    cgPurchasePlan.setPayDate(date);
                }
            }
            //查询库存数量
            cgPurchasePlan.setStockNums(0f);
            cgPurchasePlan.setType(createCgPlan.getCgType());
            cgPurchasePlan.setMacType(createCgPlan.getType());
            super.insert(cgPurchasePlan);
        }

        return null;
    }
    @Override
    public boolean updateCgPurchasePlan(CgPurchasePlan cgPurchasePlan) {

        float total= cgPurchasePlan.getActNums()*cgPurchasePlan.getPrice();
        DecimalFormat df = new DecimalFormat("#.00");
        String totalStr = df.format(total);
        cgPurchasePlan.setTotal(totalStr);
        boolean b = updateById(cgPurchasePlan);
        return b;
    }

    @Override
    public Page<CgPurchasePlan> selectCgPurchasePlan(Page<CgPurchasePlan> page, QueryCgPuchasePlan queryCgPuchasePlan) {
        DecimalFormat df = new DecimalFormat("#.00");
        Wrapper<CgPurchasePlan> wrapper=new EntityWrapper<>();
        if (AdscmBaseUtils.getInstance().isNotEmpty(queryCgPuchasePlan.getSupplier(),null)){
            wrapper.eq("sid",queryCgPuchasePlan.getSupplier());
        }
        if (AdscmBaseUtils.getInstance().isNotEmpty(queryCgPuchasePlan.getBom(),null)){
            wrapper.eq("bid",queryCgPuchasePlan.getBom());
        }
        if (AdscmBaseUtils.getInstance().isNotEmpty(queryCgPuchasePlan.getMakeNo(),null)){
            wrapper.like("make_no",queryCgPuchasePlan.getMakeNo());
        }
        if (AdscmBaseUtils.getInstance().isNotEmpty(queryCgPuchasePlan.getType(),null)){
            wrapper.eq("type",queryCgPuchasePlan.getType());
        }
        if (AdscmBaseUtils.getInstance().isNotEmpty(queryCgPuchasePlan.getState(),null)){
            wrapper.eq("state",queryCgPuchasePlan.getState());
        }
        wrapper.orderBy("sid",true);
        page = super.selectPage(page, wrapper);
        List<CgPurchasePlan> cgPurchasePlans = page.getRecords();
        for (CgPurchasePlan cgPurchasePlan : cgPurchasePlans) {
         if (AdscmBaseUtils.getInstance().isNotEmpty(cgPurchasePlan.getBid(),null)){
             CgMaterial cgMaterial = cgMaterialMapper.selectById(cgPurchasePlan.getBid());
             cgPurchasePlan.setBomName(cgMaterial);
         }
         if (AdscmBaseUtils.getInstance().isNotEmpty(cgPurchasePlan.getSid(),null)){
             CgSupplier cgSupplier = cgSupplierMapper.selectById(cgPurchasePlan.getSid());
             cgPurchasePlan.setSupplierName(cgSupplier.getName());
         }
         if (AdscmBaseUtils.getInstance().isNotEmpty(cgPurchasePlan.getCreator(),null)){
             JyUser jyUser = jyUserMapper.selectById(cgPurchasePlan.getCreator());
             cgPurchasePlan.setCreatorName(jyUser.getName());
         }
         if (AdscmBaseUtils.getInstance().isNotEmpty(cgPurchasePlan.getMacType(),null)){
             JyDrawingType jyDrawingType = jyDrawingTypeMapper.selectById(cgPurchasePlan.getMacType());
             cgPurchasePlan.setMacTypeName(jyDrawingType.getName());
         }
         if (AdscmBaseUtils.getInstance().isNotEmpty(cgPurchasePlan.getBid(),null)){
             Wrapper<JqylMaterial> jqylMaterialWrapper=new EntityWrapper<>();
             jqylMaterialWrapper.eq("RESOURCENAME",cgPurchasePlan.getBid().toString());
             jqylMaterialWrapper.eq("TASKSTATE",1);
             jqylMaterialWrapper.eq("TASKFINISHSTATE",0);
             jqylMaterialWrapper.eq("ISREVIEWTASK",0);
             List<JqylMaterial> jqylMaterials = jqylMaterialMapper.selectList(jqylMaterialWrapper);
             Double remaining=0d;
             for (JqylMaterial jqylMaterial : jqylMaterials) {
                 remaining=remaining+jqylMaterial.getRemainingnums();
             }
            cgPurchasePlan.setStockNums(Float.valueOf(String.valueOf(remaining)));
         }
        }
        page.setTotal(super.selectCount(wrapper));
        return page;
    }

    @Override
    public Boolean approve(Long id) {
        Boolean aBoolean = approveCgPurchasePlan(id);
        return aBoolean;
    }

    @Override
    public Boolean approves( List<Long> ids) {
        for (Long id : ids) {
            approveCgPurchasePlan(id);
        }
        return true;
    }
    @Transactional(rollbackFor = Exception.class)
    public  Boolean approveCgPurchasePlan(Long id){
       synchronized (this){
        //查询这个条记录
           CgPurchasePlan cgPurchasePlan = super.selectById(id);
           if (AdscmBaseUtils.getInstance().isNotEmpty(cgPurchasePlan,null)){
               if ( cgPurchasePlan.getIsNeedBuy()==0){
                   //不要购买
               }else {
                   //根据令号和供应商去查询待办任务如果没得救生成如果有就不生成了
                   Wrapper<CgTask> cgTaskWrapper =new EntityWrapper<>();
                   cgTaskWrapper.eq("supplier",cgPurchasePlan.getSid());
                   cgTaskWrapper.eq("make_no",cgPurchasePlan.getMakeNo());
                   List<CgTask> cgTasks = cgTaskMapper.selectList(cgTaskWrapper);
                   CgTask  cgTask =new CgTask();
                   if (cgTasks!=null && cgTasks.size()>0){
                       cgTask= cgTasks.get(0);
                   }else {
                       //没得就生成一个cgTask
                       cgTask.setSupplier(cgPurchasePlan.getSid());
                       cgTask.setMakeNo( cgPurchasePlan.getMakeNo().toString());
                       cgTask.setCreateTime(new Date());
                       cgTask.setCreator(cgPurchasePlan.getCreator());
                       cgTask.setState(0);
                       cgTask.setIsArrive(0);
                       cgTask.setIsCheckUp(0);
                       cgTask.setIsDeliver(0);
                       cgTask.setIsPay(0);
                       cgTask.setIsReceiveInvoice(0);
                       cgTask.setIsStart(0);
                       cgTask.setIsStockUp(0);
                       cgTaskMapper.insert(cgTask);
                   }
                   //根据id和令号查询这个
                   Wrapper<CgTaskDetail> cgTaskDetailWrapper=new EntityWrapper<>();
                   cgTaskDetailWrapper.eq("plan_id",cgPurchasePlan.getId());
                   cgTaskDetailWrapper.eq("bom_name",cgPurchasePlan.getBid());
                   List<CgTaskDetail> cgTaskDetails = cgTaskDetailMapper.selectList(cgTaskDetailWrapper);
                   if (!(cgTaskDetails!=null && cgTaskDetails.size()>0)){
                       CgTaskDetail cgTaskDetail=new CgTaskDetail();
                       cgTaskDetail.setTid(cgTask.getId());
                       cgTaskDetail.setPlanId(cgPurchasePlan.getId());
                       cgTaskDetail.setBomName(cgPurchasePlan.getBid());
                       cgTaskDetail.setNums(cgPurchasePlan.getActNums());
                       cgTaskDetail.setPrice(cgPurchasePlan.getPrice());
                       cgTaskDetail.setActPrice(cgPurchasePlan.getPrice());
                       cgTaskDetail.setTotal(Float.valueOf(cgPurchasePlan.getTotal()));
                       cgTaskDetail.setPlanArriveTime(cgPurchasePlan.getPlanArriveDate());
                       cgTaskDetail.setPlanPayTime(cgPurchasePlan.getPayDate());
                       cgTaskDetail.setUse(1);
                       cgTaskDetail.setPlanOrderTime(cgPurchasePlan.getOrderDate());
                       cgTaskDetail.setCreator(cgPurchasePlan.getCreator());
                       CgMaterial cgMaterial = cgMaterialMapper.selectById(cgPurchasePlan.getBid());
                       if (AdscmBaseUtils.getInstance().isNotEmpty(cgMaterial,null)){
                           cgTaskDetail.setType(cgMaterial.getType());
                       }
                       cgTaskDetail.setCreateTime(new Date());
                       cgTaskDetailMapper.insert(cgTaskDetail);
                   }
               }
               cgPurchasePlan.setState(1);
               super.updateById(cgPurchasePlan);

           }

       }
        return null;
    }
}
